import { Sequelize, DataTypes } from "sequelize"
import { DbBuilder } from "../general/producer"
require("@/support/tool.js")

// 数据库连接
export function testInsert() {
    const sqlite3 = require("sqlite3").verbose()
        // 之后使用用户 settings 来创建数据库文件。
    let db = new sqlite3.Database("databases/zsctask.db", function() {
        db.run(`INSERT INTO "main"."test"("id", "name", "description", "starttime") VALUES ('1', 'nsa', 'sas', '2021-08-30 12:12:00')`, function(err) {
            if (!err) {
                db.all("select * from test", function(err, data) {
                    console.log('12345')
                    if (!err) {
                        console.log(data)
                    }
                })
            }
        })
    })
}

// 测试数据库连接
export async function testInsertOrm() {
    console.log("test insert orm")
    const sequelize = new Sequelize({
        host: 'localhost',
        dialect: 'sqlite',
        storage: 'databases/zsctask.db'
    });

    try {
        await sequelize.authenticate()
        console.log("connect success!")
    } catch (error) {
        console.error("Unable to connect to the database : " + error)
    }
}

const sequelize = new Sequelize({
    dialect:'sqlite',
    storage: "databases/zsctask.db"
})

/*
 * 定义每个业务表
 */

const TaskList = sequelize.define('TaskList', {
  // 在这里定义模型属性
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  starttime: {
    type: DataTypes.STRING,
    allowNull: false
  },
  period: {
    type: DataTypes.STRING,
    allowNull: false
  },
  lastScanTime: {
    // 上次进行扫描生成任务的时间
    // 如果为空，就作为第一生成处理
    type: DataTypes.STRING,
    allowNull: true
  }
}, {
  freezeTableName: true
});

/**
 * 获取所有计划
 */
export async function allTask() {
    try{
        let rs = await TaskList.findAll()
        return rs
    }catch(error) {
        console.log("查询失败:" + error)
    }
}

/**
 * 插入新计划 tasklist
 */
export async function insertTask(form) {
    try{
        await TaskList.create(form)
    }catch(error) {
        console.log("插入失败:" + error)
    }
}



/**
 * 从任务列表生成今日任务
 */
export async function genTodayTask() {
  try {
        console.log("today task")
    let tasks = await TaskList.findAll()
    tasks.forEach( async (task)=>{
      if(!task.lastScanTime) {
        await TaskToday.create({pid: task.id, today: new Date().format("yyyy-MM-dd"), status: 0})
      } else {
        // 生成多天
        let pastday = dateDiffToday(task.lastScanTime)
        let tasktas = []
        while(pastday --) {
          let t = {pid: task.id, today: new Date().format("yyyy-MM-dd"), status: 0}
          tasktas.push(t)
        }
        await TaskToday.bulkCreate(tasktas)
        let data = await TaskToday.findAll()
        console.log("data")
        console.log(data)
      }
      // 更新扫描时间
      task.lastScanTime = new Date().format("yyyy-MM-dd")
      await task.save()
    })
  }catch(error) {
    console.error("生成失败：" + error)
  }
}

/**
 * 从今日任务中，生成历史任务归档
 */
export async function genHistoryTask() {
  return
}


const TaskToday = sequelize.define('TaskToday', {
  // 在这里定义模型属性
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  pid: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  today: {
    type: DataTypes.STRING,
    allowNull: false
  },
  status: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
}, {
  freezeTableName: true
});

/**
 * 获取所有今日任务
 */
export async function allHistoryTask() {
    try{
        let rs = await TaskToday.all()
        return rs
    }catch(error) {
        console.log("插入失败:" + error)
    }
}

/**
 * 更新今日任务状态
 */
export async function updateTodayTaskStatus(form) {
    try{
        const task = await TaskToday.findAll({id: form.id})
        task.status = form.status
    }catch(error) {
        console.log("更新失败:" + error)
    }
}

const TaskHistory = sequelize.define('TaskHistory', {
  // 在这里定义模型属性
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  pid: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  happentime: {
    type: DataTypes.STRING,
    allowNull: false
  },
  status: {
    type: DataTypes.STRING,
    allowNull: false
  },
}, {
  freezeTableName: true
});

/**
 * 获取所有历史任务
 */
export async function allTodayTask() {
    try{
        let rs = await TaskHistory.all()
        return rs
    }catch(error) {
        console.log("插入失败:" + error)
    }
}


/*
 * 初始化同步表
 */
export async function initTables() {
    try{
        // 创建文件
        await DbBuilder("zsctask.db")

        // 创建/同步表
        await TaskList.sync({alter: true})
        // await TaskToday.sync({alter: true})
        // await TaskHistory.sync({alter: true})

    } catch(error) {
        console.error("错误:" + error)
    }
}

/*
 * 更新定时任务
 */
export async function execTables() {
  try{
    await genTodayTask()
  }catch(error) {
    console.error("错误：" + error)
  }
}

const dateDiffToday = function(d1) {
  let nd1, nds1,days
  nds1 = d1.split("-")
  if(nds1.length != 3) return ""
  nd1 = new Date(nds1[1]+"-"+nds1[2]+"-"+nds1[0])
  days = parseInt((new Date() - nd1) / 1000 / 60 / 60 / 24 ) 
  if(days < 0) { return "-1" }
  return days
}
